package com.pan.download3.ctrl;

import com.pan.download3.ctrl.BlockCtrl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 这个是用来控制写入文件的
 */
public class WriteCtrl {
    private FileWriter fileWriter;

    private String bookName;

    private BlockCtrl blockCtrl;

    private Integer chapterNumber;


    public WriteCtrl(String bookName,String saveDirPath,BlockCtrl blockCtrl){

        this.chapterNumber = -1;
        this.blockCtrl = blockCtrl;
        this.bookName = bookName;

        File dirFile = null;
        String dirPath = "";
        if (saveDirPath != null){
            File file = new File(saveDirPath);
            if (file.exists()){
                dirFile = file;
                dirPath = saveDirPath;
            }else {
                throw new RuntimeException(saveDirPath+"该路径不存在");
            }
        }else {
            dirPath = System.getProperty("user.dir")+"\\story";
            dirFile = new File(dirPath);
        }
        if (!dirFile.exists()) dirFile.mkdir();
        String bookPath = dirPath + "\\"+bookName+".txt";
        File bookFile = new File(bookPath);
        if (!bookFile.exists()){
            try {
                bookFile.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        try {
            fileWriter = new FileWriter(bookFile,true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public WriteCtrl(String bookName, BlockCtrl blockCtrl){
        this(bookName,null,blockCtrl);
    }

    /**
     * 调用的时候如果返回false，调用者要写把自己用 blockCtrl阻塞起来
     * @param content
     * @param chapterOrder
     * @return
     */
    synchronized public boolean append(String content, Integer chapterOrder){
        if (this.chapterNumber !=  chapterOrder -1 ) return false;
        try {
            fileWriter.write(content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        this.chapterNumber = chapterOrder;
        blockCtrl.wakeUp(this.chapterNumber+1);
        return true;
    }

}
